package com.edu.hre.struts.action.pim;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.edu.hre.common.encrypt.Encrypter;
import com.edu.hre.common.utils.BeanFinder;
import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.common.utils.RequestUtils;
import com.edu.hre.common.utils.StringConstants;
import com.edu.hre.db.pojo.HreEmployee;
import com.edu.hre.db.pojo.HreUser;
import com.edu.hre.db.pojo.HreUserRoleScreen;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.utils.Compare;
import com.edu.hre.struts.form.pim.EmpLoginDetailUpdateForm;
import com.google.gwt.http.client.Response;

public class EmpLoginDetailUpdateAction extends Action {

	private static final Logger logger = Logger.getLogger(EmpLoginDetailUpdateAction.class);
	private static final BaseService baseService = BeanFinder.getBean(BaseService.BEAN_NAME, BaseService.class);
	private final String ACTION_NAME = "empLoginDetailUpdate";
	
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		CommonUtils.println(CommonUtils.getSourceCodeLocation());
		
		String idStr = request.getParameter("id");

		HreUser tpUser = (HreUser) request.getSession().getAttribute(RequestUtils.Attribute.USER_INFO);
		if (!EmployeeListAction.isAllowedToViewEmployeeList(tpUser, CommonUtils.parseInt(idStr, -1))) {
			response.sendError(Response.SC_BAD_REQUEST);
			return null;
		}
		
		// Get the authorization of the current user for the specified operations. 
		HreUserRoleScreen userRoleScreen = (HreUserRoleScreen) request.getSession().getAttribute(RequestUtils.Attribute.HreUserRoleScreen);
		
		EmpLoginDetailUpdateForm beanForm = (EmpLoginDetailUpdateForm) form;
		beanForm.setUpdatable(userRoleScreen.isCanUpdate());
		beanForm.setIsAddNew(false);

		if(request.getParameter("btnUpdate") == null){

			int id = CommonUtils.getIntParameter("id", request);
			EmployeeListAction.setAttributesForRequest(id, request);

			HreEmployee tmp = baseService.getFirstPojo("empNumber", Compare.EQUAL, id, null, null, 0, HreEmployee.class);
			
			if (tmp == null) {
				beanForm.setMessage(StringConstants.BLANK);
				beanForm.setSuccess(false);
				return mapping.findForward(ACTION_NAME);
			}
			
			beanForm.setEmpNumber(tmp.getEmpNumber());
			beanForm.setUsername(tmp.getMainUsername());
			
			beanForm.setMessage(StringConstants.BLANK);
			beanForm.setSuccess(false);
			return mapping.findForward(ACTION_NAME);
		}
		
		EmployeeListAction.setAttributesForRequest(beanForm.getEmpNumber(), request);
		
		String oldPassword = CommonUtils.normalizeString(beanForm.getOldPassword());
		HreUser tmpUser = null; 
		
		try {
			tmpUser = baseService.getFirstPojoAnd(new String[]{"empNumber", "userPassword"},
					new int[]{Compare.EQUAL, Compare.EQUAL}, 
					new Object[]{beanForm.getEmpNumber(), Encrypter.encodeMD5(oldPassword)}, null, null, 0, HreUser.class);
		} catch (Exception e) {
			beanForm.setMessage("Some errors occured when the system tried to execute authentication! Please try again later!");
			beanForm.setSuccess(false);
			return mapping.findForward(ACTION_NAME);
		}
		
		if (tmpUser == null) {
			beanForm.setMessage("Current password is not correct!");
			beanForm.setSuccess(false);
			return mapping.findForward(ACTION_NAME);
		}

		String newPassword = beanForm.getNewPassword();
		String confirmPassword = beanForm.getConfirmPassword();

		String verifyPass = CommonUtils.verifyPassword(newPassword);
		if (!StringConstants.BLANK.equals(verifyPass)) {
			beanForm.setMessage(verifyPass);
			beanForm.setSuccess(false);
			return mapping.findForward(ACTION_NAME);
		}
		
		if (confirmPassword == null || !confirmPassword.equals(newPassword)) {
			beanForm.setMessage("Confirm password does not match!");
			beanForm.setSuccess(false);
			return mapping.findForward(ACTION_NAME);
		}

		tmpUser.setUserPassword(Encrypter.encodeMD5(newPassword));
		tmpUser.setDateModified(new Date());

		boolean status = baseService.saveOrUpdate(tmpUser);
		if (!status) {
			beanForm.setMessage(StringConstants.UPDATE_FAILURE_MESSAGE);
			beanForm.setSuccess(false);
			return mapping.findForward(ACTION_NAME);
		}

		beanForm.setMessage("Login details have been updated successfully!");
		beanForm.setSuccess(true);
		return mapping.findForward(ACTION_NAME);
	}
}